package controller.upms;

import base.response.OffsetLimitPage;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import controller.common.BaseController;
import controller.common.StaticConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import response.CommonResult;
import services.upms.AccountServices;
import services.upms.RoleServices;
import util.cryptogram.MD5Util;
import validator.*;
import wt.entity.company.CompanyInfo;
import wt.entity.staff.StaffInfo;
import wt.entity.upms.Account;
import wt.entity.upms.Role;
import wt.entity.upms.RoleExample;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("upms/account")
public class AccountController extends BaseController {

    @Autowired
    AccountServices accountServices;
    @Autowired
    RoleServices roleServices;


    @RequiresPermissions("upms:account:default")
    @RequestMapping("index")
    public String index() {
        return "upms/account/index";
    }

    @RequiresPermissions("upms:account:default")
    @RequestMapping("editDlg")
    public String editDlg(@RequestParam(value = "id", required = false) String id, Map map) throws Exception {

        RoleExample roleExample = new RoleExample();
        roleExample.createCriteria().andLiveEqualTo((short) 1);
        List<Role> roleAll = roleServices.selectByExample(roleExample);
        map.put("role", roleAll);

        if (id != null) {
            Account account = accountServices.selectByPrimaryKey(id);
            if (account == null) {
                map.put(StaticConstant.ERROR_MESSAGE, StaticConstant.NOT_FOUND_DATA);
                return StaticConstant.ERROR_DLG;
            }
            map.put("data", account);
            map.put(StaticConstant.EDIT_URL, "upms/account/update");
            map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_UPDATE);
        } else {
            map.put(StaticConstant.EDIT_URL, "upms/account/insert");
            map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_INSERT);
        }
        return "upms/account/editDlg";
    }

    @RequiresPermissions("upms:account:default")
    @ResponseBody
    @RequestMapping("insert")
    public CommonResult insert(Integer subjectType, String subjectName, Account account, @RequestParam(value = "permission[]") List permissionList) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();
        FluentValidator fluentValidator = FluentValidator.checkAll().failOver()
                .on(subjectType, new SizeFluentValidator(1, 2, "主体类型"))
                .on(account.getPassword(), new NotEmptyFluentValidator("密码"))
                .on(account.getLive(), new NotNullFluentValidator("状态"))
                .on(account.getRoleId(), new NotNullFluentValidator("角色"))
                .on(permissionList, new NotEmptyArrayFluentValidator("权限"));

        if (subjectType == 1) {//1 企业
            fluentValidator
                    .on(subjectName, new NotBlankFluentValidator("企业名称"))
                    .on(account.getLoginName(), new NotBlankFluentValidator("组织机构代码"));

        } else {//2 市局员工
            fluentValidator
                    .on(subjectName, new NotBlankFluentValidator("姓名"))
                    .on(account.getLoginName(), new NotBlankFluentValidator("登录名"));
        }
        ComplexResult result = fluentValidator.doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            commonResult.addMessage(result);
            return commonResult.setError();
        }


        account.setCreateTime(new Date());
        if (subjectType == 1) {//1 企业
            return insertCompanyAccount (commonResult, subjectName, account, permissionList);
        } else {//2 市局员工
            return insertStaffAccount (commonResult, subjectName, account, permissionList);
        }
    }

    private CommonResult insertCompanyAccount(CommonResult commonResult, String companyName, Account account, List permissionList) throws Exception {

        CompanyInfo companyInfo=new CompanyInfo();
        companyInfo.setCompanyCode(account.getLoginName());
        companyInfo.setName(companyName);
        accountServices.insertSelective(account, permissionList,companyInfo);
        return commonResult.setSuccess();

    }
    private CommonResult insertStaffAccount(CommonResult commonResult, String staffName, Account account, List permissionList) throws Exception {

        StaffInfo staffInfo=new StaffInfo();
        staffInfo.setUserId(account.getLoginName());
        staffInfo.setName(staffName);
        accountServices.insertSelective(account, permissionList,staffInfo);
        return commonResult.setSuccess();

    }




    @RequiresPermissions("upms:account:default")
    @ResponseBody
    @RequestMapping("update")
    public CommonResult update(Account account, @RequestParam(value = "permission[]") List permissionList) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();
        ComplexResult result = FluentValidator.checkAll().failOver()
                .on(account.getLive(), new NotNullFluentValidator("状态"))
                .on(account.getRoleId(), new NotNullFluentValidator("角色"))
                .on(permissionList, new NotEmptyArrayFluentValidator("权限"))
                .on(permissionList)
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            commonResult.addMessage(result);
            return commonResult.setError();
        }
        account.setPassword(null);
        accountServices.updateByPrimaryKeySelective(account, permissionList);
        return commonResult.setSuccess();
    }

    @RequiresPermissions("upms:account:default")
    @ResponseBody
    @RequestMapping("updatePassword")
    public CommonResult updatePassword(String accountId, String password) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();
        if (StringUtils.isBlank(password)) {
            commonResult.addMessage("密码不能为空");
            return commonResult;
        }
        Account account = new Account();
        account.setId(accountId);
        account.setPassword(MD5Util.md5Hex(password));
        accountServices.updateByPrimaryKeySelective(account);
        return commonResult.setSuccess();
    }

    @RequiresPermissions("upms:account:default")
    @RequestMapping("updatePasswordDlg")
    public String updatePasswordDlg(String id, Map map) throws Exception {
        Account account = accountServices.selectByPrimaryKey(id);
        map.put("data", account);
        map.put(StaticConstant.EDIT_URL, "upms/account/updatePassword");
        map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_UPDATE);
        return "upms/account/updatePasswordDlg";
    }


    @RequiresPermissions("upms:account:default")
    @ResponseBody
    @RequestMapping("select")
    public OffsetLimitPage select(Integer limit, Integer offset, String name, String loginName, String roleId) throws Exception {
        return accountServices.selectToMainShow(name, loginName, roleId, limit, offset);
    }

}
